#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>

// 原文链接: https://blog.csdn.net/hsy12342611/article/details/128077264
// ./udp_server 9090
// ./udp_client 9090

int main(int argc, char **argv)
{
    if (argc < 0) {
        printf("a.out {port}");
        return -1;
    }

    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(fd == -1)
    {
        perror("socket");
        exit(0);
    }

    struct sockaddr_in addr;
    unsigned short port = port;
    sscanf(argv[1], "%hu", &port);
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = INADDR_ANY;
    int ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret == -1)
    {
        perror("bind");
        exit(0);
    }
    printf("bind port %d, wait client connect ...\n", port);
    char buf[1024];
    char ipbuf[64];
    struct sockaddr_in cliaddr;
    unsigned int len = sizeof(cliaddr);

    while(1)
    {
        memset(buf, 0, sizeof(buf));
        int rlen = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)&cliaddr, &len);
        printf("client info, ip: %s, port: %d\n",
               inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, ipbuf, sizeof(ipbuf)),
               ntohs(cliaddr.sin_port));
        printf("recvfrom client say: %s\n", buf);
        sendto(fd, buf, rlen, 0, (struct sockaddr*)&cliaddr, sizeof(cliaddr));
    }

    close(fd);

    return 0;
}